from socket import socket, AF_INET, SOCK_STREAM
from struct import pack
from NetworkMessage import NetMsg

REQUEST_BASIC_SERVER_INFO 	= 0x01
REQUEST_SERVER_OWNER_INFO	= 0x02
REQUEST_MISC_SERVER_INFO	= 0x04
REQUEST_PLAYERS_INFO		= 0x08
REQUEST_SERVER_MAP_INFO		= 0x10
REQUEST_EXT_PLAYERS_INFO	= 0x20
REQUEST_PLAYER_STATUS_INFO	= 0x40
REQUEST_SERVER_SOFTWARE_INFO	= 0x80

class OTStatus(object):
    
    def __init__(self, ip, port=7171):
	self.ip = ip
	self.port = port
    
    def _connect(self):
	s = socket(AF_INET, SOCK_STREAM)
	s.connect((self.ip, self.port))
	return s

    def getXMLInfo(self):
	s = self._connect()
	msg = NetMsg()
	msg.addByte(0xFF)
	msg.addByte(0xFF)
	msg.addRawString("info")
	s.send(msg.getPreparedMsg())
	ret = s.recv(8192)
	s.close()
	return ret
    
    def _getBinaryInfoPck(self,rq):
	flags = 0
	for f in rq:
	    flags = flags | f
	ret = NetMsg()
	ret.addByte(0xFF)
	ret.addByte(0x01)
	ret.addU32(flags)

	return ret.getPreparedMsg()
    
    def getBinaryInfo(self, requests):
	s = self._connect()
	s.send(self._getBinaryInfoPck(requests))
	ret = s.recv(8192)
	s.close()
	if len(ret) == 0:
	    return 0
	info = {}
	msg = NetMsg(ret)
	while True:
	    b = msg.getByte()
	    if b == 0x10 :
		info[REQUEST_BASIC_SERVER_INFO] = (msg.getString(),msg.getString(),msg.getString())
	    elif b == 0x11 :
		info[REQUEST_SERVER_OWNER_INFO] = (msg.getString(),msg.getString())
	    elif b == 0x12 :
		info[REQUEST_MISC_SERVER_INFO] = (msg.getString(),msg.getString(),msg.getString(), msg.getU64())
	    elif b == 0x20:
		info[REQUEST_PLAYERS_INFO] = (msg.getU32(),msg.getU32(),msg.getU32())
	    elif b == 0x30:
		info[REQUEST_SERVER_MAP_INFO] = (msg.getString(), msg.getString(), msg.getU16(), msg.getU16())
	    elif b == 0x21:
		size = msg.getU32()
		ls = []
		for _ in range(0,size):
		    ls.append((msg.getString(), msg.getU32()))
		info[REQUEST_EXT_PLAYERS_INFO] = ls
	    elif b == 0x23:
		info[REQUEST_SERVER_SOFTWARE_INFO] = (msg.getString(),msg.getString(),msg.getString())
	    if msg.isEnd():
		break
	
	return info



if __name__ == "__main__":
    stat = OTStatus(ip="wypas.eu")
    stats = stat.getBinaryInfo((REQUEST_BASIC_SERVER_INFO,
				    REQUEST_SERVER_OWNER_INFO,
				    REQUEST_MISC_SERVER_INFO,
				    REQUEST_PLAYERS_INFO,
				    REQUEST_SERVER_MAP_INFO,
				    REQUEST_EXT_PLAYERS_INFO,
				REQUEST_SERVER_SOFTWARE_INFO))
				
    print ''.join(str(i) for i in stats[REQUEST_SERVER_MAP_INFO])